param (
    [Parameter(Mandatory=$true)]
    [string]$WslInstance
)

# Check if WSL instance exists
if (-not (wsl --list --quiet | Where-Object { $_ -eq $WslInstance })) {
    Write-Error "WSL instance '$WslInstance' not found."
    exit 1
}

# Install Docker
wsl -d $WslInstance -u root bash -c @'
apt-get update && apt-get install -y \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg \
    lsb-release \
    axel  # 安装 axel

# 使用国内阿里云Docker镜像源
curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null

# 使用apt安装docker
apt-get update && apt-get install -y docker-ce docker-ce-cli containerd.io

# 配置国内镜像源
mkdir -p /etc/docker
echo '{
  "registry-mirrors": [
    "https://docker.m.daocloud.io",
    "https://hub-mirror.c.163.com",
    "https://dockerproxy.com",
    "https://docker.mirrors.ustc.edu.cn",
    "https://docker.nju.edu.cn"
  ]
}' > /etc/docker/daemon.json

# 安装docker-compose，使用 axel 替代 curl
axel -n 10 -o /usr/local/bin/docker-compose "https://get.daocloud.io/docker/compose/releases/download/$(curl -s https://api.github.com/repos/docker/compose/releases/latest | grep '\"tag_name\":' | sed -E 's/.*\"([^\"]+)\".*/\1/')/docker-compose-$(uname -s)-$(uname -m)"
chmod +x /usr/local/bin/docker-compose
ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

# Configure Docker to use current user
groupadd docker || true
usermod -aG docker $(whoami)
systemctl enable docker
systemctl start docker
'@

# Verify installation
$dockerVersion = wsl -d $WslInstance -u root docker --version
$composeVersion = wsl -d $WslInstance -u root docker-compose --version

Write-Host "`n=== Installation Summary ==="
Write-Host "Docker version: $dockerVersion"
Write-Host "Docker Compose version: $composeVersion"
Write-Host "`nDocker and Docker Compose have been successfully installed in WSL instance '$WslInstance'"